package de.nonspectare.utils;

import java.io.File;
import java.io.FileWriter;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;

public class AntInvoker {

	private File buildFile;
	private Project project;

	public AntInvoker(File buildFile) {
		super();
		this.buildFile = buildFile;
		this.project = this.initBuildFile();
	}

	private Project initBuildFile() {
		Project p = new Project();
		p.setUserProperty("ant.file", this.buildFile.getAbsolutePath());
		DefaultLogger consoleLogger = new DefaultLogger();
		consoleLogger.setErrorPrintStream(System.err);
		consoleLogger.setOutputPrintStream(System.out);
		consoleLogger.setMessageOutputLevel(Project.MSG_INFO);
		p.addBuildListener(consoleLogger);

		return p;
	}

	public void testAnt() {

		File buildFile = this.buildFile;
		Project p = new Project();
		p.setProperty("ant.file", buildFile.getAbsolutePath());
		p.init();
		ProjectHelper helper = ProjectHelper.getProjectHelper();
		p.addReference("ant.projectHelper", helper);
		helper.parse(p, buildFile);
		p.executeTarget(p.getDefaultTarget());
	}

	public void changeProperty(String propertyName, String value) {
		this.project.setProperty(propertyName, value);
	}

	public void callDefaultAntTask() {
		// Quelle:
		// http://www.ibm.com/developerworks/websphere/library/techarticles/0502_gawor/0502_gawor.html
		try {
			this.project.fireBuildStarted();
			this.project.init();
			ProjectHelper helper = ProjectHelper.getProjectHelper();
			this.project.addReference("ant.projectHelper", helper);
			helper.parse(this.project, buildFile);
			this.project.executeTarget(this.project.getDefaultTarget());
			this.project.fireBuildFinished(null);
		} catch (BuildException e) {
			this.project.fireBuildFinished(e);
		}
	}
}
